# -*- coding: utf-8 -*-
import copy
import random
from datetime import datetime
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from zc_core.util.http_util import retry_request
from zc_core.spiders.base import BaseSpider
from ispacechina.rules import *
from zc_core.dao.item_data_dao import ItemDataDao
from zc_core.util.batch_gen import time_to_batch_no


class SaleSpider(BaseSpider):
    name = 'sale'
    sale_url = 'https://mall.ispacechina.com/rest/service/routing/nouser/qrySaleNumService'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(SaleSpider, self).__init__(batchNo=batchNo, *args, **kwargs)

    def start_requests(self):
        item_list = ItemDataDao().get_batch_data_list(self.batch_no, fields={'_id': 1, 'supplierId': 1},
                                                      query={'soldCount': {'$exists': False}})
        self.logger.info('目标：%s' % (len(item_list)))
        random.shuffle(item_list)
        for item in item_list:
            sku_id = item.get('_id')
            sp_id = item.get('supplierId')
            yield Request(
                method='POST',
                url=self.sale_url,
                body=json.dumps({
                    "supplierId": sp_id,
                    "skuId": sku_id,
                    "skuLocation": '2'
                }),
                meta={
                    'reqType': 'order',
                    'batchNo': self.batch_no,
                    'skuId': sku_id,
                    'supplierId': sp_id,
                },
                headers={
                    'Host': 'mall.ispacechina.com',
                    'Connection': 'keep-alive',
                    'Pragma': 'no-cache',
                    'Cache-Control': 'no-cache',
                    'Accept': 'application/json, text/javascript, */*; q=0.01',
                    'Origin': 'https://mall.ispacechina.com',
                    'X-Requested-With': 'XMLHttpRequest',
                    'Content-Type': 'application/json',
                    'Referer': 'https://mall.ispacechina.com/html/portal/goodsDetail.html?skuId={}&supplierId={}&searchType=2'.format(
                        sku_id, sp_id),
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                },
                callback=self.parse_sales,
                errback=self.error_back,
            )

    # 处理销量
    def parse_sales(self, response):
        meta = response.meta
        sku_id = meta.get('skuId')
        data = parse_sales(response)
        if data:
            self.logger.info('商品: [%s]' % sku_id)
            yield data
        else:
            self.logger.error('销量异常: [%s]' % sku_id)
